import axios from "axios";
import { ElMessage } from "element-plus";
import router from "../router/index.js";
// let baseUrl = 'http://localhost:3000/admin/api'
let baseUrl = process.env.VUE_APP_API_URL || '/admin/api'

// 新建分类列表
export function postNewCategory(result, value) {
    console.log(result);
    return axios.post(`${baseUrl}/rest/${result}`, value)
}

// 获取分类列表
export function getList(result) {
    return axios.get(`${baseUrl}/rest/${result}`)
}

// 获取分类详情
export function getDetail(result, id) {
    return axios.get(`${baseUrl}/rest/${result}/${id}`)
}
// 修改分类列表
export function putDetail(result, id, value) {
    return axios.put(`${baseUrl}/rest/${result}/${id}`, value)
}

// 删除分类列表
export function deleteList(result, id) {
    return axios.delete(`${baseUrl}/rest/${result}/${id}`)
}

// 登录
export function logins(value) {
    return axios.post(`${baseUrl}/login`, value)
}

// 请求拦截
axios.interceptors.request.use(res => {
    // 添加请求头信息 
    // 获取请求头 后端全部用小写 前端用大写
    if (localStorage.token) {
        res.headers.Authorization = 'Bearer ' + localStorage.token
    }
    return res
}, err => {
    return Promise.reject(err)
})

// 响应拦截
axios.interceptors.response.use(res => {
    return res
}, err => {
    console.log(err)
    if (err.response.data.message) {
        ElMessage({
            type: "error",
            message: err.response.data.message,
        });
        if (err.response.status == 401) {
            console.log(45646)
            router.push({ path: '/login' })
        }
    }
    return Promise.reject(err)
})


export default {
    postNewCategory, getList, getDetail, putDetail, deleteList, logins
}

